﻿
using AutoMapper;
using Microsoft.AspNetCore.Http;
using MiniErp.Common.Cache;
using MiniErp.Common.DB.MySqlDB;
using MiniErp.Entity.DataStreams.BOs;
using MiniErp.Entity.DataStreams.DOs;
using MiniErp.Entity.DataStreams.DTOs;
using MiniErp.Entity.DataStreams.DTOs.Users;
using MiniErp.Entity.JWTs;
using MiniErp.Repository.BaseRepository;
using MiniErp.Repository.MysqlRepository.IRepository;
using MiniErp.Repository.UnitOfWorkCore;
using MiniErp.Service.BusinessService.IService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace MiniErp.Service.BusinessService.Service
{
    public class UserService : BaseService, IUserService
    {
        private readonly BaseRepository<MysqlContext, UserInfo> _uir;
        private readonly BaseRepository<MysqlContext, JobsSystemsRights> _jsrr;
        private readonly ICache _cache;
        public UserService(ICache cache, IMysqlUnitOfWork mysqlUnitOfWork, IMapper mapper) : base(mysqlUnitOfWork, mapper)
        {
            _uir = mysqlUnitOfWork.CreateRepository<MysqlContext, UserInfo>();
            _jsrr = mysqlUnitOfWork.CreateRepository<MysqlContext, JobsSystemsRights>();
            _cache = cache;
        }


        public async Task<UserDTO> Login(int uid, string password)
        {
            if (uid == 0 || string.IsNullOrWhiteSpace(password))
            {
                throw new ExceptionBO("用户名或者密码不能为空");
            }
            var num = await _uir.GetInfoNumsAsync(item => item.UId == uid);
            if (num == 0)
            {
                throw new ExceptionBO($"不存在工号为{uid}的用户");
            }
            else if (num == 1)
            {
                var userInfo = await _uir.GetReadOnlyInfoAsync(item => item.UId == uid && item.PassWord == password);
                if (userInfo == null)
                {
                    throw new ExceptionBO("用户名或者密码错误");
                }
                //更新该用户的权限缓存
                await _cache.SetAsync(CacheKeyType.Right, userInfo.UId.ToString(), await GetUserRightByMysql(userInfo.JobsId));
                return _mapper.Map<UserDTO>(userInfo);
            }
            throw new ExceptionBO("该用户账号信息异常");
        }



        public async Task<bool> Register(RegisterDTO registers)
        {
            //生成新用户
            var users = _mapper.Map<UserInfo>(registers);
            users.State = true;
            _uir.AddInfo(users);
            return await _mysqlUnitOfWork.SaveAsync() == 0
                ? throw new ExceptionBO("注册失败")
                : true;
        }


        public async Task<List<CacheUserRights>> GetUserRightByMysql(int JobsId)
        {
            var jsrresult = await _jsrr.GetInfoAsyncs(item => item.JobsId == JobsId);
            var list = new List<CacheUserRights>();
            jsrresult.ForEach(item =>
            {
                list.Add(
                        new CacheUserRights
                        {
                            SystemsRoute = item.Systems.SystemsRoute,
                            RightName = item.Rights.RightName
                        });
            });
            return list;
        }

        public List<string> GetUserPunchInfo(int uid)
        {

            var postData = string.Format("username={0}&submit={1}", uid, "查询");
            var data = new ASCIIEncoding().GetBytes(postData);
            //向服务端请求
            var httpRequset = WebRequest.Create("http://183.63.20.253:8008/consume/login.php") as HttpWebRequest;
            httpRequset.Method = "POST";
            httpRequset.ContentType = "application/x-www-form-urlencoded";
            httpRequset.ContentLength = data.Length;
            httpRequset.CookieContainer = new CookieContainer();
            httpRequset.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36";
            httpRequset.Accept = "text/html, application/xhtml+xml, */*";
            try
            {
                using var newStream = httpRequset.GetRequestStream();
                newStream.Write(data, 0, data.Length);
            }
            catch
            {
                throw new ExceptionBO("打卡系统连接异常", 404);
            }
            //将请求的结果发送给客户端(界面、应用)
            var myResponse = httpRequset.GetResponse() as HttpWebResponse;
            var cookie = myResponse.Cookies;
            try
            {
                using var reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                var returnHtml = reader.ReadToEnd();
                var start = "<tr><td>考勤刷卡時間</td></tr>";
                var end = "</table>";
                var posStart = returnHtml.IndexOf(start) + start.Length;
                var posEnd = returnHtml.IndexOf(end) - end.Length;
                var result = Regex.Split(returnHtml.Substring(posStart, (posEnd - posStart + end.Length)).Trim(), "</tr>", RegexOptions.IgnoreCase);
                for (var i = 0; i < result.Length; i++)
                {
                    result[i] = result[i].Replace("<tr>", "").Replace("<td>", "").Replace("</td>", "").Trim();
                }
                return result.Where(item => !string.IsNullOrEmpty(item)).ToList();
            }
            catch
            {
                throw new ExceptionBO("打卡系统查询异常", 404);
            }
        }
    }
}
